#!/bin/bash
# File Name = novnc
# Author = jph
# chkconfig: 2345 70 45
# description: novnc start|stop|status|restart script
novnc_dir=/usr/local/vnc/noVNC
start()
{
	stat
	ns=$?	
	if [ $ns -eq 0 ]; then
		echo "noVNC already Running"
	else
		echo "starting noVNC"
		$novnc_dir/quick_start.sh
		echo "[success]"
	fi
}

stop()
{	
	stat
	ns=$?
	if [ $ns -eq 1 ]; then 
		echo 'noVNC already Stopped'
		return	
	fi
	python $novnc_dir/utils/websockify/clearToken.py 1>/dev/null 2>&1
	while [ $ns -eq 0 ]; do
		echo -e "Stopping noVNC:\c"
		lsof -i:6090|awk 'NR==2{print $2}'|xargs kill -9
		echo "[success]"	
		stat
		ns=$?
	done
}

status()
{
	echo -e "noVNC status:\c"
	pid=$(lsof -i:6090|awk 'NR==2{print $2}')
	if [ ! -n "$pid" ]; then
		echo "[Stopped]"
		return 1
	else
		echo "[running]"	
		return 0
	fi
}

stat()
{
	pid=$(lsof -i:6090|awk 'NR==2{print $2}')
	if [ ! -n "$pid" ]; then
		return 1
	else
		return 0
	fi
}

case "$1" in
start)
	start
	;;
stop)
	stop
	;;
restart)
	stop
	start
	;;
status)
	status
	;;
*)
	echo "Usage :$0 start|stop|restart|status"
	exit 0;
esac
exit
